# 导入视图集
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from books.models import BookInfo
from books.serialziers import BookModelSerializer
# 导入权限类方法
from rest_framework.permissions import IsAuthenticated
# 导入认证的类方法
from rest_framework.authentication import BasicAuthentication,SessionAuthentication
#  导入限流类方法
from rest_framework.throttling import UserRateThrottle
# 导入排序方法类
from rest_framework.filters import OrderingFilter
# 导入自定义分页器
from books.utils import NumPage


class BooksView(ModelViewSet):
    # 指定查询集属性
    queryset = BookInfo.objects.all()
    # 指定序列化器属性
    serializer_class = BookModelSerializer

    # 局部认证和权限
    # 权限
    permission_classes = [IsAuthenticated]
    # 认证
    authentication_classes = [BasicAuthentication, SessionAuthentication]
    # 限流
    # throttle_classes = (UserRateThrottle,)
    # 视图类限流 制定限流名称
    throttle_scope = 'modelviewset'
    # 制定结果返回时的过滤字段,按照指定字段进行信息过滤
    filter_fields = ('btitle','bread')
    # 指定排序方法
    filter_backends = [OrderingFilter]
    # 指定排序字段
    ordering_fields = ['id', 'bread']
    # 指定自定义分页器
    pagination_class = NumPage



    # 获取最后一本图书,通过action装饰通知自动生成路由方法，怎么生成路由
    # method 指定该方法匹配的请求方式，detail指定需不需要匹配id值 false是不需要
    @action(methods=['get'],detail=False)
    def last_book(self,request):
        book = BookInfo.objects.last()
        ser = self.get_serializer(book)
        return Response(ser.data)